/**
 * Created by Administrator on 2015/2/6.
 */
var AJAX_URL = "http://www.12301.cc/call/jh_prod_f.php";
	//delete : "http://www.12301.cc/call/jh_prod_f.php?action=delete",//删除
	//query : "http://www.12301.cc/call/jh_prod_f.php?action=search" //模糊搜索
var createLink = 'http://www.12301.cc/prod_edits_child.html';
var Edit = (function(){
	var QUERY_INPUT_INIT_VAL = "";
	var ajaxObj = null;
	var Delay = new PFT_GLOBAL.U.Delay();
	//数组操作封装
	var doArray = {
		getArrayIndex : function(array,item){
			var index = -1;
			for(var i in array){
				if(item == array[i]){
					index = Number(i);
					break;
				}
			}
			return index;
		},
		sortUp : function(array,item){
			var result = [];
			var index = this.getArrayIndex(array,item);
			if(index<1) return false;
			for(var i in array){
				i = Number(i);
				if(i==index-1){
					result[i] = array[i+1];
				}else if(i==index){
					result[i] = array[i-1];
				}else{
					result[i] = array[i];
				}
			}
			return result;
		},
		sortDown : function(array,item){
			var result = [];
			var index = this.getArrayIndex(array,item);
			if(index<0 || index==array.length-1) return false;
			for(var i in array){
				i = Number(i);
				if(i==index){
					result[i] = array[i+1];
				}else if(i==index+1){
					result[i] = array[i-1];
				}else{
					result[i] = array[i];
				}
			}
			return result;
		},
		remove : function(array,item){
			var index = this.getArrayIndex(array,item);
			if(index<0) return false;
			array.splice(index,1);
			return array;
		},
		add : function(array,item){
			return array.push(item);
		}
	};
	var getLid = function(){
		return $("#lid_hideInp").val();
	};
	var getSortId = function(){
		var ids = [];
		$("#childListUl").children().each(function(){
			ids.push($(this).data("id"));
		})
		return ids.join(",");
	};
	var upDateSort = function(lid,sortids,config){
		if(!lid){
			console && console.log("lid不存在");
			return false;
		}
		if(!sortids && sortids!==""){
			console && console.log("sortid不存在");
			return false;
		}
		config = config || {};
		var fn = new Function;
		var loading = config.loading || fn;
		var removeLoading = config.loading || fn;
		var timeout = config.timeout || function(){console && console.log("updRelation接口请求超时")};
		var serverError = config.serverError || function(){console && console.log("updRelation接口请求服务器出错")};
		var success = config.success || function(){console && console.log("updRelation接口请求成功")};
		var fail = config.fail || function(){console && console.log("updRelation接口请求失败")};
		var error = config.error || function(){console && console.log("updRelation接口请求出错")};
		PFT_GLOBAL.G.Ajax({
			url : AJAX_URL,
			type : "POST",
			dataType : "JSON",
			data : {
				action : "updRelation",
				lid : lid,
				sort : sortids
			},
			loading : function(){loading()},
			removeLoading : function(){removeLoading()},
			timeout : function(){ timeout()},
			serverError : function(){ serverError()}
		},function(res){
			if(res.status == "success"){
				success();
			}else if(res.status == "fail"){
				fail();
			}else{
				error();
			}
		})
	};
	function init(){
		QUERY_INPUT_INIT_VAL = $("#querykeyInp").val();
		$("#childListWrap").on("click",".col_3 .close",function(e){ //删除
			var target = $(e.currentTarget);
			var result = window.confirm("确定要删除此景点吗");
			if(!result) return false;
			var item = target.parents(".citem");
			removeHandle(item);
		}).on("click",".col_3 a.up",function(e){ //向上移动
			var target = $(e.currentTarget);
			var item = target.parents(".citem");
			if(item.children(".flag").hasClass("first")) return false;
			sortHandle("up",item);
		}).on("click",".col_3 a.down",function(e){ //向下移动
			var target = $(e.currentTarget);
			var item = target.parents(".citem");
			if(item.index()==$("#childListUl").children().length-1) return false;
			sortHandle("down",item);
			return false;
		})
		//保存按钮
		$("#saveToNextBtn").on("click",function(e){
			$("#nextFlag").val("");
			submit();
		})
		//保存进入下一页按钮
		$("#saveToNextGoBtn").on("click",function(e){
			$("#nextFlag").val(1);
			submit();
		})
		$("#querykeyInp").on("input propertychange",function(e){
			var keyword = $(this).val();
			var len = keyword.length;
			if(len>=2){
				Delay.clear();
				Delay.set(function(){
					ajaxObj && ajaxObj.abort && ajaxObj.abort();
					ajaxObj = query(keyword);
				},500)
			}else{
				$("#queryResultUl").hide();
			}
		}).on("click",function(e){
			var inp = $(this);
			var val = inp.val();
			if(val.length<=1) return false;
			if(val !== QUERY_INPUT_INIT_VAL){
				query(val);
			}else{
				$("#queryResultUl").hide();
				inp.val("")
			}
			return false;
		}).on("blur",function(e){
			var inp = $(this);
			var val = inp.val();
			if(val == ""){
				inp.val(QUERY_INPUT_INIT_VAL);
			}
		})

		$(document).on("click",function(e){
			$("#queryResultUl").hide();
		})
		$("#queryResultUl").on("click",function(e){
			$("#queryResultUl").show();
			e.stopPropagation();
		}).on("click",".qitem .addBtn",function(e){
			var target = $(e.currentTarget);
			var item = target.parents(".qitem");
			var id = item.data("id");
			var province = item.data("province");
			var city = item.data("city");
			var name = item.find(".lt").text();
			addChildHandle({
				id : id,
				province : province,
				city : city,
				name : name
			})
			return false;
		})

		$("#addChildBtn").on("click",function(e){
			var lid = $("#lid").val();
			var val = $("#querykeyInp").val();
			var next = $("#next").val();
			if(!val) return false;
			window.location.href = "http://www.12301.cc/prod_edits_child.html?lid="+lid+"&title="+val+"&nf="+next;
			return false;
		})

		var nextFlag = $("#nextFlag").val();
		if(nextFlag==1){
			$("#saveToNextGoBtn").css("display","inline-block");
		}

	}

	/**
	 * 前移&后移
	 * @param type "up"&"down"
	 * @param item
	 * @returns {boolean}
	 */
	function sortHandle(type,item){
		var id = item.data("id");
		if(!id || !type) return false;
		var sortIds = getSortId().split(",");
		var nSortIds = type=="up" ? doArray.sortUp(sortIds,id) : doArray.sortDown(sortIds,id);
		if(!nSortIds) return false;
		nSortIds = nSortIds.join(",");
		var lid = getLid();
		var tip = type=="up" ? "前移" : "后移";
		upDateSort(lid,nSortIds,{
			loading : function(){},
			removeLoading : function(){},
			timeout : function(){},
			serverError : function(){console && console.log(tip+"服务器出错");},
			success : function(){
				console && console.log(tip+"成功");
				type=="up" ? sortUp(item) : sortDown(item);
			},
			fail : function(){console && console.log(tip+"失败");}
		})
	}

	/**
	 * 删除子景点
	 * @param item
	 */
	function removeHandle(item){
		var data = {};
		var id = item.attr("data-id");
		var lid = getLid();
		var items = $("#childListUl").children().filter(function(){
			return $(this).attr("data-id") !== id;
		});
		items.each(function(){
			var item = $(this);
			var id = item.attr("data-id");
			var inputChecked = item.find("input:checked");
			var checkVal = inputChecked.length ? 1 : 0;
			data[id] = checkVal;
		})
		var sortIds = PFT_GLOBAL.U.JSON.stringify(data);
		upDateSort(lid,sortIds,{
			loading : function(){},
			removeLoading : function(){},
			success : function(){
				PFT_GLOBAL.U.Alert("success",'<p style="width:160px">删除成功</p>',1.5 * 1000);
				item.remove();
				restor();
			},
			fail : function(){
				PFT_GLOBAL.U.Alert("fail",'<p style="width:160px">删除失败</p>',1.5 * 1000);
			}
		})
	}

	/**
	 * 添加选中景点到子景点列表
	 * @param data
	 */
	function addChildHandle(data){
		var data = data || {};
		var id = data.id;
		var name = data.name;
		var province = data.province || "";
		var city = data.city || "";
		var lid = getLid();
		var html = "";
		//判断待添加的景点在子景点更表中是否存在，若存在则不添加
		var checkExist = function(id){
			var exist = false;
			$("#childListUl").children().each(function(index){
				var item = $(this);
				var _id = item.data("id");
				if(id == _id){
					exist = true;
					return false;
				}
			})
			return exist;
		};
		var buildHtml = function(data){
			data = data || {};
			var html = "";
			var id = data.id;
			var lid = $("#lid_hideInp").val();
			var name = data.name;
			var province = data.province;
			var city = data.city;
			html += '<li class="citem" data-id="'+id+'">';
			html += '	<div class="con clearfix">';
			html += '	<div class="col col_1">';
			html += '	<p class="jqname">'+name+'</p>';
			html += '	<p class="jqarea">'+province+' '+city+'</p>';
			html += '	</div>';
			html += '	<div class="col col_2"><a href="###"><img class="daoma" src="http://www.12301.cc/images/prod_child_list_daoma.png" alt=""/></a></div>';
			html += '	<div class="col col_3">';
			html += '	<a class="do down" href="###"><i class="cpicon down"></i><i class="cpicon down-hover hover"></i></a>';
			html += '	<a class="do up" href="###"><i class="cpicon up"></i><i class="cpicon up-hover hover"></i></a>';
			html += '	<a class="do edit" href="prod_edits_child.html?lid='+lid+'&type=b&id='+id+'" target="_blank"><i class="cpicon edit"></i><i class="cpicon edit-hover hover"></i></a>';
			html += '	<a class="do close" href="###"><i class="cpicon close"></i><i class="cpicon close-hover hover"></i></a>';
			html += '	</div>';
			html += '	</div>';
			html += '	<span class="flag cpicon"><?=$key+1?></span>';
			html += '</li>';
			return html;
		};
		//若该景点已存在于子景点列表 则不添加
		if(checkExist(id)){
			alert("此景点在列表中已存在,不能重复添加");
			return false;
		}
		var sortIds = getSortId();
		if(!sortIds){
			sortIds = id;
		}else{
			sortIds = sortIds+","+id;
		}
		upDateSort(lid,sortIds,{
			loading : function(){},
			removeLoading : function(){},
			success : function(res){
				console && console.log("添加成功");
				$("#childListUl").append(buildHtml({
					id : id,
					lid : lid,
					name : name,
					city : city,
					province : province
				}));
				setTimeout(function(){
					restor();
				},100)
			},
			fail : function(){console && console.log("添加失败")},
			error : function(){console && console.log("添加接口-出错")},
			serverError : function(){ console && console.log("添加接口-服务器出错")}
		})
	}

	function sortUp(item){
		var prevItem = item.prev();
		if(!prevItem.length) return false;
		item.insertBefore(prevItem);
		restor();
	}
	function sortDown(item){
		var nextItem = item.next();
		if(!nextItem.length) return false;
		item.insertAfter(nextItem);
		restor();
	}
	/**
	 * 重新排序
	 * @returns {boolean}
	 */
	function restor(){
		$("#childListWrap").find(".citem .flag").removeClass("first").each(function(index){
			var flag = $(this);
			if(index==0){
				flag.addClass("first")
			}else{
				flag.text(index);
			}
		})
	}

	/**
	 * 保存提交表单
	 */
	function submit(){
		var data = {};
		$("#childListUl").children().each(function(index,item){
			var item = $(this);
			var id = item.attr("data-id");
			var checkbox = item.find(".con .col_4 input:checked");
			var status = checkbox.length ? 1 : 0;
			data[id] = status;
		})
		$("#formData").val(PFT_GLOBAL.U.JSON.stringify(data));
		$("#submitForm").submit();
	}


	/**
	 * 模糊搜索
	 * @param keyword
	 */
	function query(keyword){
		if(!keyword) return false;
		PFT_GLOBAL.G.Ajax({
			url : AJAX_URL,
			type : "GET",
			dataType : "JSON",
			data : {
				action : "search",
				k : keyword
			},
			loading : function(){},
			removeLoading : function(){},
			tiemout : function(){},
			serverError : function(){}
		},function(res){
			var html = "";
			if(res && res.state=="ok" && res.list){
				$("#queryResultUl").show();
				var data = res.list;
				if(data.length){
					for(var i=0; i<res.list.length; i++){
						var d = data[i];
						var id = d["id"];
						var name = d["scenic_name"];
						var province = d["province_cn"];
						var city = d["city_cn"];
						html += '<li class="qitem clearfix" data-id="'+id+'" data-province="'+province+'" data-city="'+city+'"><span class="lt">'+name+'</span><a class="rt addBtn" href="###">添加</a></li>';
					}
					$("#queryResultUl").html(html);
				}else{
					var parameters = '?title='+keyword,lid = $("#lid").val(),next=$("#next").val();
					if(lid) parameters+='&lid='+lid;
					parameters+="&nf="+next;
					$("#queryResultUl").html('<li class="empty">暂无与<span style="margin:0 2px; color:#0998d9">'+keyword+'</span>相匹配景点,您可以此为名称创建子景点<a id="queryEmptyToCreatBtn" href="'+createLink+parameters+'">创建</a></li>')
				}
			}else{
				$("#queryResultUl").hide();
				console && console.log("error");
			}
		})
	}

	return{init:init}

})();


$(function(){Edit.init();})